package com.demo.function.jdk.date;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * localtime使用
 */
@Slf4j
public class LocalTimeService {

    /**
     * 字符串时间集合转LocalTime对象集合，并且排序
     */
    public List<String> sortTime() {
        List<String> list = List.of("10:00:01", "10:00:00", "23:59:59", "05:00:00");
        log.info("time:{}", list);

        List<LocalTime> times = sort(list);

        return times.stream().map(LocalTime::toString).collect(Collectors.toList());
    }

    /**
     * 字符串时间集合转LocalTime对象集合，从集合里获取第一个大于当前时间的值
     */
    public LocalTime getNextTime(List<String> times) {
        List<LocalTime> list = sort(times);

        LocalTime now = LocalTime.now();
        for (LocalTime localTime : list) {
            if (now.compareTo(localTime) < 0) {
                return localTime;
            }
        }
        return null;
    }

    /**
     * 通过时间转换成日期时间对象
     * @param time 时间
     * @return localdatetime
     */
    public LocalDateTime getLocalDateTime(LocalTime time) {
        return time.atDate(LocalDate.now());
    }

    private List<LocalTime> sort(List<String> times) {
        List<LocalTime> list = times.stream().map(s -> {
            String[] split = s.split(":");
            return LocalTime.of(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
        }).sorted().collect(Collectors.toList());
        log.info("排序后时间：{}", times);
        return list;
    }
}
